<template>
    <div class="report-container">
        <!-- 面包屑导航 -->
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>数据统计</el-breadcrumb-item>
            <el-breadcrumb-item>数据报表</el-breadcrumb-item>
        </el-breadcrumb>


        <!-- 数据概览 -->
        <el-row :gutter="20" class="data-overview">
            <el-col :span="6">
                <el-card shadow="hover">
                    <template #header>
                        <div class="card-header">
                            <span>总销售额</span>
                            <el-tag type="success" effect="plain">本月</el-tag>
                        </div>
                    </template>
                    <div class="card-content">
                        <h2>¥{{ totalSales.toLocaleString() }}</h2>
                        <div class="trend">
                            <span :class="salesTrend >= 0 ? 'up' : 'down'">
                                {{ Math.abs(salesTrend) }}%
                                <el-icon><component :is="salesTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                            </span>
                            <span class="label">同比上月</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card shadow="hover">
                    <template #header>
                        <div class="card-header">
                            <span>订单总数</span>
                            <el-tag type="warning" effect="plain">本月</el-tag>
                        </div>
                    </template>
                    <div class="card-content">
                        <h2>{{ totalOrders }}</h2>
                        <div class="trend">
                            <span :class="orderTrend >= 0 ? 'up' : 'down'">
                                {{ Math.abs(orderTrend) }}%
                                <el-icon><component :is="orderTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                            </span>
                            <span class="label">同比上月</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card shadow="hover">
                    <template #header>
                        <div class="card-header">
                            <span>商品总数</span>
                            <el-tag type="info" effect="plain">当前</el-tag>
                        </div>
                    </template>
                    <div class="card-content">
                        <h2>{{ totalProducts }}</h2>
                        <div class="trend">
                            <span class="label">库存商品数量</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card shadow="hover">
                    <template #header>
                        <div class="card-header">
                            <span>用户总数</span>
                            <el-tag type="primary" effect="plain">当前</el-tag>
                        </div>
                    </template>
                    <div class="card-content">
                        <h2>{{ totalUsers }}</h2>
                        <div class="trend">
                            <span :class="userTrend >= 0 ? 'up' : 'down'">
                                {{ Math.abs(userTrend) }}%
                                <el-icon><component :is="userTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                            </span>
                            <span class="label">同比上月</span>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 图表区域 -->
        <el-row :gutter="20" class="chart-container">
            <el-col :span="12">
                <el-card class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <span>热销商品TOP10</span>
                        </div>
                    </template>
                    <div ref="hotProductsChart" class="chart"></div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <span>商品分类占比</span>
                        </div>
                    </template>
                    <div ref="categoryChart" class="chart"></div>
                </el-card>
            </el-col>
        </el-row>

        <el-row :gutter="20" class="chart-container">
            <el-col :span="24">
                <el-card class="chart-card">
                    <template #header>
                        <div class="card-header">
                            <span>销售趋势</span>
                            <el-radio-group v-model="salesChartType" size="small">
                                <el-radio-button label="week">周</el-radio-button>
                                <el-radio-button label="month">月</el-radio-button>
                                <el-radio-button label="year">年</el-radio-button>
                            </el-radio-group>
                        </div>
                    </template>
                    <div ref="salesChart" class="chart"></div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import { ArrowRight, ArrowUp, ArrowDown } from '@element-plus/icons-vue'

// 日期选择器快捷选项
const dateShortcuts = [
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        }
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        }
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        }
    }
]

// 数据概览
const totalSales = ref(0)
const totalOrders = ref(0)
const totalProducts = ref(0)
const totalUsers = ref(0)
const salesTrend = ref(0)
const orderTrend = ref(0)
const userTrend = ref(0)

// 获取数据概览
const getOverview = async () => {
    try {
        const res = await axios.get('http://127.0.0.1:8000/api/statistics/overview/')
        if (res.data.code === 200) {
            const { sales, orders, products, users } = res.data.data
            totalSales.value = sales.total
            totalOrders.value = orders.total
            totalProducts.value = products.total
            totalUsers.value = users.total
            salesTrend.value = parseFloat(sales.rate)
            orderTrend.value = orders.rate
            userTrend.value = users.rate
        }
    } catch (error) {
        console.error('获取数据概览失败:', error)
    }
}

// 图表相关
const salesChart = ref(null)
const categoryChart = ref(null)
const hotProductsChart = ref(null)
const orderChart = ref(null)
const salesChartType = ref('month')
const dateRange = ref([])

let charts = []

// 初始化销售趋势图
const initSalesChart = async () => {
    try {
        if (!salesChart.value) {
            console.warn('销售趋势图表容器未找到，跳过初始化')
            return
        }
        
        await nextTick() // 确保DOM渲染完成
        
        const chart = echarts.init(salesChart.value)
        charts.push(chart)
        
        const res = await axios.get('http://127.0.0.1:8000/api/statistics/trend/')
        if (res.data.code === 200) {
            const trendData = res.data.data.filter(item => item.sales > 0 || item.orders > 0)
            const dates = trendData.map(item => item.date)
            const sales = trendData.map(item => item.sales)
            const orders = trendData.map(item => item.orders)
            
            const option = {
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: ['销售额', '订单量']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: dates
                },
                yAxis: [
                    {
                        type: 'value',
                        name: '销售额',
                        axisLabel: {
                            formatter: '{value} 元'
                        }
                    },
                    {
                        type: 'value',
                        name: '订单量',
                        axisLabel: {
                            formatter: '{value} 单'
                        }
                    }
                ],
                series: [
                    {
                        name: '销售额',
                        type: 'line',
                        smooth: true,
                        data: sales,
                        itemStyle: {
                            color: '#409EFF'
                        }
                    },
                    {
                        name: '订单量',
                        type: 'line',
                        smooth: true,
                        yAxisIndex: 1,
                        data: orders,
                        itemStyle: {
                            color: '#67C23A'
                        }
                    }
                ]
            }
            
            chart.setOption(option)
        }
    } catch (error) {
        console.error('初始化销售趋势图表失败:', error)
    }
}

// 初始化商品分类占比图
const initCategoryChart = async () => {
    try {
        if (!categoryChart.value) {
            console.warn('商品分类图表容器未找到，跳过初始化')
            return
        }
        
        await nextTick() // 确保DOM渲染完成
        
        const chart = echarts.init(categoryChart.value)
        charts.push(chart)
        
        const res = await axios.get('http://127.0.0.1:8000/api/statistics/products/')
        if (res.data.code === 200) {
            const categoryStats = res.data.data.category_stats
            const legendData = categoryStats.map(item => item.category__name)
            const seriesData = categoryStats.map(item => ({
                value: item.count,
                name: item.category__name
            }))
            
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 10,
                    data: legendData
                },
                series: [
                    {
                        name: '商品分类',
                        type: 'pie',
                        radius: ['50%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '20',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: seriesData
                    }
                ]
            }
            
            chart.setOption(option)
        }
    } catch (error) {
        console.error('初始化商品分类图表失败:', error)
    }
}

// 初始化热销商品图
const initHotProductsChart = async () => {
    try {
        if (!hotProductsChart.value) {
            console.warn('热销商品图表容器未找到，跳过初始化')
            return
        }
        
        await nextTick() // 确保DOM渲染完成
        
        const chart = echarts.init(hotProductsChart.value)
        charts.push(chart)
        
        const res = await axios.get('http://127.0.0.1:8000/api/statistics/products/')
        if (res.data.code === 200) {
            const hotProducts = res.data.data.hot_products
            const productNames = hotProducts.map(item => item.name)
            const salesData = hotProducts.map(item => item.sales)
            
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    boundaryGap: [0, 0.01]
                },
                yAxis: {
                    type: 'category',
                    data: productNames.length ? productNames : ['暂无数据']
                },
                series: [
                    {
                        name: '销售量',
                        type: 'bar',
                        data: salesData.length ? salesData : [0],
                        itemStyle: {
                            color: function(params) {
                                const colorList = ['#FF4500','#FF6347','#FA8072','#FFA07A','#FFB6C1',
                                                 '#FFC0CB','#FFE4E1','#F08080','#E9967A','#DC143C']
                                return colorList[params.dataIndex]
                            }
                        },
                        label: {
                            show: true,
                            position: 'right'
                        }
                    }
                ]
            }
            
            chart.setOption(option)
        }
    } catch (error) {
        console.error('初始化热销商品图表失败:', error)
    }
}

// 初始化订单统计图
const initOrderChart = async () => {
    try {
        if (!orderChart.value) {
            console.warn('订单状态图表容器未找到，跳过初始化')
            return
        }
        
        await nextTick() // 确保DOM渲染完成
        
        const chart = echarts.init(orderChart.value)
        charts.push(chart)
        
        const res = await axios.get('http://127.0.0.1:8000/api/statistics/products/')
        if (res.data.code === 200) {
            const orderStatus = res.data.data.order_status
            const defaultData = [
                { value: 0, name: '已完成' },
                { value: 0, name: '待付款' },
                { value: 0, name: '待发货' },
                { value: 0, name: '已取消' },
                { value: 0, name: '退款中' }
            ]
            
            const option = {
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    top: '5%',
                    left: 'center'
                },
                series: [
                    {
                        name: '订单状态',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: true,
                            formatter: '{b}: {c} ({d}%)'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '20',
                                fontWeight: 'bold'
                            }
                        },
                        data: orderStatus.length ? orderStatus : defaultData
                    }
                ]
            }
            
            chart.setOption(option)
        }
    } catch (error) {
        console.error('初始化订单状态图表失败:', error)
    }
}

// 处理日期变化
const handleDateChange = async () => {
    if (!dateRange.value) return
    
    const [startDate, endDate] = dateRange.value
    const params = {
        start_date: startDate.toISOString().split('T')[0],
        end_date: endDate.toISOString().split('T')[0]
    }
    
    try {
        // 重新获取所有数据
        await Promise.all([
            getOverview(),
            initSalesChart(),
            initCategoryChart(),
            initHotProductsChart(),
            initOrderChart()
        ])
    } catch (error) {
        console.error('更新数据失败:', error)
    }
}

// 监听销售图表类型变化
watch(salesChartType, (newVal) => {
    // TODO: 根据类型获取对应数据
    console.log('图表类型改变:', newVal)
})

// 监听窗口大小变化，重绘图表
const handleResize = () => {
    charts.forEach(chart => chart.resize())
}

onMounted(async () => {
    // 获取数据概览
    await getOverview()
    
    // 使用nextTick确保DOM渲染完成后再初始化图表
    await nextTick()
    
    // 初始化所有图表
    await Promise.all([
        initSalesChart(),
        initCategoryChart(),
        initHotProductsChart(),
        initOrderChart()
    ])
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
    // 移除事件监听
    window.removeEventListener('resize', handleResize)
    // 销毁图表实例
    charts.forEach(chart => chart.dispose())
})
</script>

<style scoped>
.report-container {
    padding: 20px;
    height: calc(100vh - 80px);
    overflow-y: auto;
}

.filter-card {
    margin-bottom: 20px;
}

.data-overview {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-content {
    text-align: center;
}

.card-content h2 {
    margin: 10px 0;
    font-size: 28px;
    color: #303133;
}

.trend {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
    font-size: 14px;
}

.trend .up {
    color: #67C23A;
}

.trend .down {
    color: #F56C6C;
}

.trend .label {
    color: #909399;
}

.chart-container {
    margin-bottom: 20px;
}

.chart-card {
    margin-bottom: 20px;
}

.chart {
    height: 350px;
}
</style>
